<?php

require "conf.php";
require_once "data/dao/BaseDAO.php";
require_once "application/user/UserUtils.php";
require_once "utils/Validate.php";
require_once "data/dao/CollectionDAO.php";
	
class FriendCodeDAO extends BaseDAO{
	
	/**
	 * adds friend code to friend code table, checking that 
	 * the friend code is of a valid format
	 * 
	 * @param $userId
	 * @param $gameId
	 * @param $friendCode
	 * 
	 */
	public function addFriendCode($userId, $gameId, $friendCode){
		
		Validate::notNull($friendCode);
		Validate::notNull($gameId);
		Validate::isValidFriendCode($friendCode, $gameId);
		
		if(!UserUtils::userExists($userId))
			throw new Exception("Attempting to add friend code for a user that " .
					"does not exist");
					
		self::connect();
		//TODO: return false if query fails
		mysql_query("INSERT INTO " . FRIEND_CODE_TABLE . " VALUES('$friendCode', " .
				"'$userId', '$gameId')");
	}
	
	public function findFriendCode($userID, $gameID){
		
		self::connect();
		$find = mysql_query("SELECT * FROM " . FRIEND_CODE_TABLE . " WHERE" .
				" user_id = '$userID' and game_id = '$gameID'");
				
		if (mysql_num_rows($find) == 0)
			return null;
			
		while($row = mysql_fetch_assoc($find)){
			return $row['friend_code'];
		}
	}			
	
	public function deleteFriendCode($userId, $gameId){
		
		self::connect();
		mysql_query("DELETE FROM " . FRIEND_CODE_TABLE . " WHERE user_id = '$userId' " .
				"AND game_id = '$gameId'");
	}
	
	public function deleteFriendCodeById($userId){
		
		self::connect();
		mysql_query("DELETE FROM " . FRIEND_CODE_TABLE . " WHERE user_id = '$userId'");
	}
	
	/**
	 * finds users who have the same game, this is done using the title
	 * and not the id, because a game can have more than one id if locale variants
	 * exist
	 */
	public function findFriendsForGame($gameId, $userId, $title, $page){
		
		Validate::notNull($gameId);
		Validate::notNull($userId);
		Validate::notNull($title);
		
		$rowsPerPage = 20;
		
		if(!isset($page)){
			$page = 1;
		}
		
		self::connect();
		$sqlQuery = "SELECT u.id, f.friend_code
					 FROM users u " .
					"INNER JOIN games g " .
					"ON g.title = '$title' " . 
                    "INNER JOIN friend_codes f " . 
                    "ON f.user_id = u.id " .
                    "WHERE f.game_id = '$gameId' " .
                    "OR f.game_id = g.id";
                    
        $numOfRows = mysql_num_rows(mysql_query($sqlQuery));
        
        // early exit if there are no matches
		if($numOfRows == 0)
			return null; 

		// calculate the last page number
		$lastPage = ceil($numOfRows / $rowsPerPage);
		// check page is within range
		if($page > $lastPage){
			$page = $lastPage;
		}
		if($page < 1){
			$page = 1;
		}

		$limit = ' LIMIT ' .($page - 1) * $rowsPerPage .',' .$rowsPerPage;
		$sqlQuery .= $limit;
		
		$find = mysql_query($sqlQuery);
        $friends = array();
		while($row = mysql_fetch_assoc($find)){
			array_push($friends, array("user_id" => $row['id'],
									   "friend_code" => $row['friend_code']));
		}
		return new FriendsResultsView($friends, (int) $lastPage, $numOfRows);
	}
}
?>
